<script setup>
    import productApi from "@/api/product/product.js";
    import categoryApi from "@/api/product/category.js";
    import WangEditor from "@/components/WangEditor.vue";
    import 'viewerjs/dist/viewer.css'
    import {ref, reactive} from "vue";
    import {
        Delete,
        Edit,
    } from "@element-plus/icons-vue";
    import {ElMessage, ElMessageBox} from "element-plus";

    //表格数据
    const list = ref([])
    const total = ref(0)
    //分页信息和搜索条件
    const productQuery = reactive({
        name: '',
        category1Id: '',
        category2Id: '',
        category3Id: '',
        beginCreateTime: '',
        endCreateTime: '',
        page: 1,
        limit: 10
    })
    //分类搜索条件
    const searchCategoryIdList = ref([])
    const searchCategoryProps = ref({
        value: 'id',
        label: 'name',
        checkStrictly: true,    //选择任意一级选项
        lazy: true,
        lazyLoad(node, reslove) {
            //刚开始点击级联框，node.value == 'undefined',
            //所有一级分类父分类是0：node.value=0
            if (typeof node.value === 'undefined') {
                node.value = 0
            }
            categoryApi.selectByParentId(node.value).then(result => {
                if (result.code === 0) {
                    const {data} = result
                    data.forEach(categoryVO => {
                        categoryVO.leaf = !categoryVO.hasChildren
                    })
                    //返回数据
                    reslove(result.data)
                }
            })
        }
    })

    const loadData = () => {
        productApi.list(productQuery).then(result => {
            list.value = result.data.list
            total.value = result.data.total
            list.value.forEach((product) => {
                product.carouselImageList = product.carouselImage.split(',')
            })
        })
    }

    loadData()

    const onSearch = () => {
        //清空之前的条件值
        productQuery.category1Id = ''
        productQuery.category2Id = ''
        productQuery.category3Id = ''
        if (searchCategoryIdList.value !== undefined) {
            if (searchCategoryIdList.value.length === 1) {
                productQuery.category1Id = searchCategoryIdList.value[0]
            }
            if (searchCategoryIdList.value.length === 2) {
                productQuery.category1Id = searchCategoryIdList.value[0]
                productQuery.category2Id = searchCategoryIdList.value[1]
            }
            if (searchCategoryIdList.value.length === 3) {
                productQuery.category1Id = searchCategoryIdList.value[0]
                productQuery.category2Id = searchCategoryIdList.value[1]
                productQuery.category3Id = searchCategoryIdList.value[2]
            }
        }
        productQuery.page = 1;
        loadData();
    }

    //根据Id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            productApi.deleteById(id).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //批量删除
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        ids.value = rows.map(row => row.id);
        console.log(ids.value);
    }
    const deleteAll = () => {
        ElMessageBox.confirm(
            '确认要删除吗？',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                lockScroll: false //防止抖动
            }
        ).then(() => {
            productApi.deleteAll(ids.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        })
    }

    //添加和修改
    const dialogFormVisible = ref(false);
    const product = ref({})
    const title = ref()
    const categoryIdList = ref([])
    const categoryProps = ref({
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad(node, reslove) {
            //刚开始点击级联框，node.value == 'undefined',
            //所有一级分类父分类是0：node.value=0
            if (typeof node.value === 'undefined') {
                node.value = 0
            }
            categoryApi.selectByParentId(node.value).then(result => {
                if (result.code === 0) {
                    const {data} = result
                    data.forEach(categoryVO => {
                        categoryVO.leaf = !categoryVO.hasChildren
                    })
                    //返回数据
                    reslove(result.data)
                }
            })
        }
    })

    //轮播图
    const carouselList = ref([])
    /*const carouselImageList = ref([])
    const handleCarouselSuccess = (result, uploadFile) => {
        if (result.code === 0) {
            carouselImageList.value.push(result.data)
        }
    }
    const handleCarouselRemove = (uploadFile, uploadFiles) => {
        carouselImageList.value.splice(carouselImageList.value.indexOf(uploadFile.url), 1)
    }*/

    //因为取消了checkStrictly: true, //选择任意一级选项，这时候只有选中三个才会触发change事件
    const categoryChange = () => {
        product.value.category1Id = categoryIdList.value[0]
        product.value.category2Id = categoryIdList.value[1]
        product.value.category3Id = categoryIdList.value[2]
    }

    const showAddDialog = () => {
        dialogFormVisible.value = true
        title.value = '添加'
        product.value = {}
        categoryIdList.value = []
        carouselList.value = []
    }
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true
        title.value = '编辑'
        product.value = {}
        productApi.selectById(id).then(result => {
            product.value = result.data

            categoryIdList.value[0] = product.value.category1Id
            categoryIdList.value[1] = product.value.category2Id
            categoryIdList.value[2] = product.value.category3Id

            //轮播图回显
            carouselList.value = []
            const carouselImage = product.value.carouselImage.split(',')
            carouselImage.forEach(image => {
                carouselList.value.push({url: image})
            })
        })
    }

    const addOrUpdate = () => {
        //用逗号拼接轮播图字符串到：product.value.carouselImage
        const carouselImage = ref([])
        carouselList.value.forEach(item => {
            if (item.response) {
                carouselImage.value.push(item.response.data)
            } else {
                carouselImage.value.push(item.url)
            }
        })
        product.value.carouselImage = carouselImage.value.join(',')
        if (product.value.id) {
            productApi.update(product.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        } else {
            //将carouselImageList集合保存的轮播图，用逗号拼接成字符串放到product的carouselImage
            // product.value.carouselImage = carouselImageList.value.join(',')
            /*const carouselImage = ref([])
            carouselList.value.forEach(item => {
                carouselImage.value.push(item.response.data)
            })
            product.value.carouselImage = carouselImage.value.join(',')*/
            productApi.add(product.value).then(result => {
                if (result.code === 0) {
                    ElMessage({message: result.msg, type: 'success',})
                    dialogFormVisible.value = false
                } else {
                    ElMessage.error(result.msg)
                }
                loadData()
            })
        }
    }

    //富文本编辑器
    const onEditorChange = (intro) => {
        product.value.intro = intro
    }

    import { Plus } from '@element-plus/icons-vue'
    const handleAvatarSuccess = (result) => {
        product.value.image = result.data
    }

    //修改status状态
    const handleSwitchChange = (row) => {
        productApi.updateStatus(row.id, row.status).then(result => {
            if (result.code === 0) {
                ElMessage({message: result.msg, type: 'success',})
                dialogFormVisible.value = false
            } else {
                ElMessage.error(result.msg)
            }
        })
    }
</script>

<template>
    <el-card class="">
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="danger" @click="deleteAll">批量删除</el-button>
            </div>
        </template>

        <el-form :inline="true">
            <el-form-item label="商品名称">
                <el-input v-model="productQuery.name" placeholder="请输入商品名称" clearable />
            </el-form-item>
            <el-form-item label="分类">
                <el-cascader clearable
                    v-model="searchCategoryIdList"
                    :props="searchCategoryProps"
                    style="width: 100%" />
            </el-form-item>
            <el-form-item label="录入时间">
                <el-date-picker
                    v-model="productQuery.beginCreateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="productQuery.endCreateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column fixed prop="id" label="ID" width="50" />
            <el-table-column prop="name" label="商品名称"/>
            <el-table-column prop="title" label="商品标题"/>
            <el-table-column prop="category1Name" label="一级类别"/>
            <el-table-column prop="category2Name" label="二级类别"/>
            <el-table-column prop="category3Name" label="三级类别"/>
            <el-table-column prop="price" label="价格"/>
            <el-table-column prop="stock" label="库存"/>
            <el-table-column prop="image" label="主图" #default="scope">
                <viewer>
                    <img :src="scope.row.image" width="50"/>
                </viewer>
            </el-table-column>
            <el-table-column prop="carouselImageList" label="轮播图" #default="scope" width="250">
                <span v-for="item in scope.row.carouselImageList" v-viewer>
                    <img :src="item" width="50">
                </span>
            </el-table-column>
            <!--<el-table-column prop="sales" label="销量"/>-->
            <el-table-column prop="status" label="线上状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        inline-prompt
                        active-text="上架"
                        inactive-text="下架"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="录入时间"/>
            <el-table-column prop="updateTime" label="更新时间"/>
            <el-table-column fixed="right" label="操作" align="center" min-width="100">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showUpdateDialog(row.id)"/>
                    <el-button type="danger" :icon="Delete" circle @click="deleteById(row.id)"/>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="productQuery.page"
            v-model:page-size="productQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"/>

        <!--添加、编辑的弹出框-->
        <el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
            <el-form :model="product">
                <el-form-item label="商品名称" :label-width="70">
                    <el-input v-model="product.name" autocomplete="off" />
                </el-form-item>
                <el-form-item label="商品标题" :label-width="70">
                    <el-input v-model="product.title" autocomplete="off" />
                </el-form-item>
                <el-form-item label="分类" :label-width="70">
                    <el-cascader clearable
                                 v-model="categoryIdList"
                                 :props="categoryProps"
                                 @change="categoryChange"
                                 style="width: 100%" />
                </el-form-item>
                <el-form-item label="商品价格" :label-width="70">
                    <el-input v-model="product.price" autocomplete="off" />
                </el-form-item>

                <el-form-item label="主图" :label-width="70">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/product/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :headers="headers"
                    >
                        <img v-if="product.image" :src="product.image" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="轮播图" :label-width="70">
                    <el-upload
                        multiple
                        v-model:file-list="carouselList"
                        action="/api/product/upload"
                        list-type="picture-card"
                        :on-success="handleCarouselSuccess"
                        :on-remove="handleCarouselRemove"
                    >
                        <el-icon><Plus /></el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="详细描述" :label-width="70">
                    <WangEditor :initValue="product.intro" @getEditorContent="onEditorChange"
                                v-if="dialogFormVisible" @close="dialogFormVisible = false"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </el-card>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>